<template>
  <div>
    <el-upload
        :action="CMBASE.baseUploadAction"
        accept="image/jpeg,image/jpg,image/gif,image/png"
        :limit="limit"
        :on-exceed="uploadOverRun"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :on-preview="handlePictureCardPreview"
        :on-error="handleError"
        :file-list="fileList"
        :disabled="disabled"
        list-type="picture-card"
        class="app-uploader">
      <i class="el-icon-plus"/>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" top="5vh" append-to-body>
      <img style="width: 100%;height: 100%;object-fit: contain" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import CryptoJS from "_utils/crypto";

export default {
  props: {
    value: {
      type: String
    },
    fileListStr: {
      type: String
    },
    limit: {
      type: Number,
      default: 5
    },
    disabled:{
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      images: [],
      fileList: [],
      a: '',
    }
  },
  watch: {
    value(newValue, oldValue) {
      this.fillFileList(newValue);
    }
  },
  created() {
    this.fileList = [];
    if (this.value) {
      this.fileList = this.value.split(",").map((item) => ({url:  item}));
    }
    console.log(this.fileList)
  },
  methods: {
    fillFileList() {
      this.fileList = [];
      if (this.value) {
        let list = this.value.split(",")
        list.forEach(element => {
          if (element && element.length > 0) {
            this.fileList.push({url:  element})
          }
        });
      }
      console.log(this.fileList)
    },

    /* 多图上传预览 */
    handlePictureCardPreview(file) {
      console.log(file.url)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /* 多图上传限制 */
    uploadOverRun() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    /* 多图上传移除 */
    handleRemove(file, fileList) {

      let valueList = this.value.split(",")
      for (var i = 0; i < valueList.length; i++) {
        // 存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        let url
        // 后台已有照片
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.path
        }
        if (url.includes(valueList[i])) {
          valueList.splice(i, 1)
        }
      }

      this.$emit('input', valueList.join(','))
    },
    // 上传错误时的钩子
    handleError() {
      this.$message({message: '上传失败', type: 'error'})
    },
    /* 文件上传成功 */
    handleSuccess(res, fileList) {
      // 解密
      res.data = JSON.parse(CryptoJS.Decrypt(res.data))
      console.log(res.data)
      if (res.data.state === 'success') {
        let str = [...(this.value.split(",")), res.data.path].join(",");
        //如果第一个有逗号，就截取，如果没有，就不截取
        if (str.substring(0, 1) === ',') {
          str = str.substr(1)
        } else {
          str = str
        }
        this.$emit('input', str)
      } else {
        this.$message.error(res.msg + '上传失败请稍后重试！')
      }
    },
  }
}
</script>
<style>
.el-upload-list {
  display: inline-grid;
}
</style>
